package library.utils;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;

/**
 * @author Dmitry
 */
public abstract class ImageLoader extends Thread {
    private String path;

    public ImageLoader(String bookId) {
        this.path = bookId;
    }

    @Override
    public void run() {
        try {
            String imagePath = extractImagePath(path);
            if (imagePath == null) {
                return;
            }
            ByteArrayInputStream byteArrayInputStream = download(imagePath);
            if (byteArrayInputStream == null) {
                return;
            }
            BufferedImage image = ImageIO.read(byteArrayInputStream);
            onImageLoaded(image);
        } catch (IOException ex) {
            Utils.log(ex);
        }
    }

    private ByteArrayInputStream download(String path) {
        try {
            System.setProperty("http.agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2"); 
            URL url = new URL(path);
            URLConnection connection = url.openConnection();
            connection.connect();
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            if (httpConnection.getResponseCode() != 200) {
                return null;
            }
            
            InputStream stream = httpConnection.getInputStream();//url.openStream();
            ByteArrayOutputStream out;
            try (BufferedInputStream bufferedStream = new BufferedInputStream(stream)) {
                out = new ByteArrayOutputStream();
                byte[] buf = new byte[1024];
                int n = 0;
                while (-1 != (n = bufferedStream.read(buf))) {
                    boolean interupted = isInterrupted();
                    if (interupted) {
                        return null;
                    }
                    out.write(buf, 0, n);
                }
                out.close();
            } catch (IOException ex) {
                Utils.log(ex);
                return null;
            }
            byte[] response = out.toByteArray();
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(response);
            return byteArrayInputStream;
        } catch (MalformedURLException ex) {
            Utils.log(ex);
            return null;
        } catch (IOException ex) {
            Utils.log(ex);
            return null;
        }
    }

    private String extractImagePath(String bookId) {
        String url = "http://flibusta.net/b/" + bookId;
        ByteArrayInputStream str = download(url);
        if (str == null) {
            return null;
        }
        String content = Utils.inputStreamToString(str);
        return regexpEctract(content);

    }

    private String regexpEctract(String htmlContent) {
        Pattern pattern = Pattern.compile("<img src=\"([^\\\"]*?)\"\\s*alt=\"Cover image\".*?>", Pattern.DOTALL);
        Matcher matcher = pattern.matcher(htmlContent);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return null;
    }

    abstract public void onImageLoaded(BufferedImage image);
}
